package org.gd.science.kttsoft;

/**
 * @author Gorhover D. P.
 */
public class MathNotation {

    private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final char[] ALPHABET_LIST = ALPHABET.toUpperCase().toCharArray();

    /**
     * General Method:
     * Method for convert Scale Notation
     *
     * @param inputString input word
     * @param inputScale input notation scale
     * @param outputScale output notation scale
     * @return output word
     */
    public static String convertNotation(String inputString, int inputScale, int outputScale) {
        checkArguments(inputString, inputScale);
        char[] input = inputString.toUpperCase().toCharArray();
        int sum = 0;
        int step = input.length;
        for(char item: input) {
            int attribute = (int) (Math.pow(inputScale, --step));
            sum += (CharArrayUtils.indexOf(ALPHABET_LIST, item) * attribute);
        }
        if(sum < outputScale) {
            return String.valueOf(ALPHABET_LIST[sum]);
        }
        StringBuilder stringBuilder = new StringBuilder();
        int div;
        for(div = sum; div >= outputScale; div /= outputScale) {
            int mod = div % outputScale;
            stringBuilder.append(ALPHABET_LIST[mod]);
        }
        stringBuilder.append(ALPHABET_LIST[div]);
        return stringBuilder.reverse().toString();
    }

    /**
     * Secondary method:
     * Check input arguments
     *
     * @param inputString input Word
     * @param scale input scale
     */
    private static void checkArguments(String inputString, int scale) {
        if(inputString == null || inputString.isEmpty()) {
            throw new IllegalArgumentException("inputString is empty");
        }
        char[] legalAlphabet = CharArrayUtils.subList(ALPHABET_LIST, 0, scale);
        char[] input = inputString.toCharArray();
        for(char item: input) {
            if(!CharArrayUtils.contains(legalAlphabet, item)) {
                throw new IllegalArgumentException("error in input string [" + inputString + "]: not valid element [" + item + "]");
            }
        }
    }


}
